import { useMemo } from "react";
import type { ProColumns } from "@ant-design/pro-components";

interface UseColumnsOptions<T> {
  /** 列配置 */
  columns: ProColumns<T>[];
  /** 是否显示序号列 */
  showIndex?: boolean;
  /** 是否显示操作列 */
  showOption?: boolean;
}

// 默认的列属性
const defaultColumnProps = {
  width: 100,
  align: "center" as const,
  ellipsis: {
    showTitle: true,
  },
  search: false,
  copyable: false,
  formItemProps: {
    labelAlign: "right",
  },
} as const;

type ColumnConfig = {
  width?: number;
  ellipsis?: { showTitle: boolean };
  align?: "left" | "right" | "center";
  fixed?: "left" | "right";
};

/**
 * 处理表格列的 Hook
 * @template T - 表格数据类型
 */
const useColumns = <T extends Record<string, any>>(
  options: UseColumnsOptions<T>
) => {
  const { columns = [], showIndex = true } = options;

  const finalColumns = useMemo(() => {
    const result: ProColumns<T>[] = [];

    // 添加序号列
    if (showIndex) {
      result.push({
        title: "序号",
        dataIndex: "index",
        valueType: "index",
        fixed: "left",
        width: 60,
      } as ProColumns<T>);
    }

    // 处理业务列，合并默认属性
    const processedColumns = columns.map((column) => {
      // 特殊字段的默认配置
      const specialConfig: ColumnConfig = {};

      // 根据字段类型设置特殊配置
      switch (column.valueType) {
        case "textarea":
          specialConfig.width = 200;
          specialConfig.ellipsis = { showTitle: true };
          break;
        case "select":
          specialConfig.width = 120;
          break;
        case "digit":
          specialConfig.width = 100;
          specialConfig.align = "right";
          break;
        case "date":
        case "dateTime":
          specialConfig.width = 160;
          break;
        case "switch":
          specialConfig.width = 80;
          break;
        case "option":
          // 操作列的宽度根据按钮数量计算
          const buttonsCount =
            (column.render?.toString().match(/button|a/gi)?.length || 0) / 2;
          specialConfig.width = Math.max(120, buttonsCount * 64 + 32); // 每个按钮64px + 间距
          specialConfig.fixed = "right" as const;
          break;
        default:
          break;
      }

      // 合并默认属性、特殊配置和原有配置
      // 原有配置优先级最高，可以覆盖默认值
      const mergedColumn = {
        ...defaultColumnProps,
        ...specialConfig,
        ...column,
        formItemProps: {
          ...defaultColumnProps.formItemProps,
          ...column.formItemProps,
        },
      };

      return mergedColumn as ProColumns<T>;
    });

    result.push(...processedColumns);

    return result;
  }, [columns, showIndex]);

  return {
    columns: finalColumns,
  };
};

export default useColumns;
